<template>
  <div class="product-list">
    <div class="page-header">
      <h2>商品列表</h2>
      <el-button type="primary" @click="$router.push('/products/add')">添加商品</el-button>
    </div>
    
    <div class="search-bar">
      <el-input
        v-model="searchName"
        placeholder="请输入商品名称"
        class="search-input"
        clearable>
      </el-input>
      <el-select v-model="searchCategory" placeholder="请选择商品分类" clearable>
        <el-option
          v-for="item in categoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" @click="searchProducts">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="products"
      border
      style="width: 100%">
      <el-table-column
        prop="productId"
        label="商品ID"
        width="80">
      </el-table-column>
      <el-table-column
        prop="name"
        label="商品名称"
        min-width="180">
      </el-table-column>
      <el-table-column
        prop="description"
        label="商品描述"
        min-width="240">
      </el-table-column>
      <el-table-column
        prop="price"
        label="价格"
        width="100">
        <template slot-scope="scope">
          {{ scope.row.price }} 元
        </template>
      </el-table-column>
      <el-table-column
        prop="stock"
        label="库存"
        width="100">
      </el-table-column>
      <el-table-column
        prop="category"
        label="分类"
        width="120">
      </el-table-column>
      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="pagination">
    </el-pagination>
  </div>
</template>

<script>
import productApi from '@/api/product'

export default {
  name: 'ProductList',
  
  data() {
    return {
      loading: true,
      products: [],
      allProducts: [],
      searchName: '',
      searchCategory: '',
      categoryOptions: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  
  created() {
    this.fetchProducts()
  },
  
  methods: {
    // 获取商品列表
    async fetchProducts() {
      this.loading = true
      try {
        const response = await productApi.getAllProducts()
        this.allProducts = response.data
        this.extractCategories()
        this.filterProducts()
        this.loading = false
      } catch (error) {
        this.$message.error('获取商品列表失败')
        this.loading = false
      }
    },
    
    // 提取分类选项
    extractCategories() {
      const categories = [...new Set(this.allProducts.map(item => item.category))]
      this.categoryOptions = categories.filter(Boolean).map(category => ({
        value: category,
        label: category
      }))
    },
    
    // 过滤商品
    filterProducts() {
      let filtered = [...this.allProducts]
      
      // 按名称搜索
      if (this.searchName) {
        filtered = filtered.filter(item => 
          item.name.toLowerCase().includes(this.searchName.toLowerCase())
        )
      }
      
      // 按分类搜索
      if (this.searchCategory) {
        filtered = filtered.filter(item => item.category === this.searchCategory)
      }
      
      this.total = filtered.length
      
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.products = filtered.slice(start, end)
    },
    
    // 搜索商品
    searchProducts() {
      this.currentPage = 1
      this.filterProducts()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchName = ''
      this.searchCategory = ''
      this.currentPage = 1
      this.filterProducts()
    },
    
    // 编辑商品
    handleEdit(row) {
      this.$router.push(`/products/edit/${row.productId}`)
    },
    
    // 删除商品
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await productApi.deleteProduct(row.productId)
        if (response.data.success) {
          this.$message.success(response.data.message)
          if (this.products.length === 1) {
            this.currentPage--
          }
          this.fetchProducts()
        } else {
          this.$message.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除商品失败')
        }
      }
    },
    
    // 页面大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.filterProducts()
    },
    
    // 页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.filterProducts()
    }
  }
}
</script>

<style scoped>
.product-list {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>